<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="信用卡号" prop="cardNum">
            <el-input v-model="queryParams.cardNum" placeholder="请输入信用卡号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" v-if="queryParams.holderId > 0">
            <el-button type="info" @click="back()" icon="Back">返回</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['credit:card:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['credit:card:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['credit:card:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['credit:card:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="信用卡号" align="center" prop="cardNum" width="160"/>
        <!--        <el-table-column label="账号拆分模板id" align="center" prop="billTemplateId" />-->
        <el-table-column label="账单日" align="center" prop="statementDay">
          <template #default="scope">
            每月{{scope.row.statementDay}}日
          </template>
        </el-table-column>
        <el-table-column label="还款日" align="center" prop="repaymentDay" width="100">
          <template #default="scope">
            每月{{scope.row.repaymentDay}}日
          </template>
        </el-table-column>
        <el-table-column label="卡总额度" align="center" prop="totalLimit" width="120">
          <template #default="scope">
            {{scope.row.totalLimit}}元
          </template>
        </el-table-column>
        <el-table-column label="剩余额度" align="center" prop="leftLimit" width="120">
          <template #default="scope">
            {{scope.row.leftLimit}}元
          </template>
        </el-table-column>
        <el-table-column label="临时额度" align="center" prop="tempLimit" width="120">
          <template #default="scope">
            <div v-if="scope.row.tempLimit!= undefined">{{scope.row.tempLimit}}元</div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="剩余额度占有比例" align="center" prop="leftRate" />-->
        <el-table-column label="卡片状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="module_state" :value="scope.row.state" />
          </template>
        </el-table-column>
        <el-table-column label="卡片有效期" align="center" prop="periodValidity" width="120"/>
        <el-table-column label="CVV编号" align="center" prop="cardCvv" />
        <el-table-column label="持卡人" align="center" prop="realName" />
        <el-table-column label="绑定POS商户" align="center" prop="posMerName" width="160"/>
        <el-table-column label="绑定扫码商户" align="center" prop="qrMerName" width="160"/>
        <el-table-column label="POS机利率" align="center" prop="posRate" width="120">
          <template #default="scope">
            {{scope.row.posRate}}%
          </template>
        </el-table-column>
        <el-table-column label="扫码支付利率" align="center" prop="qrRate" width="120">
          <template #default="scope">
            {{scope.row.qrRate}}%
          </template>
        </el-table-column>
        <el-table-column label="绑定手机号" align="center" prop="phoneNum" width="120"/>
        <el-table-column label="银行名称" align="center" prop="bankName"  width="120"/>
        <el-table-column label="联行号" align="center" prop="bankCode" />
        <el-table-column label="绑定微信号" align="center" prop="wxNo"  width="120"/>
        <el-table-column label="绑定微信昵称" align="center" prop="wxNiceName"  width="120"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
          <template #default="scope">
            <el-tooltip content="账单详情" placement="top">
              <router-link :to="'/credit/month/record?cId=' + scope.row.id" v-hasPermi="['credit:monthRecord:list']" style="margin-right: 10px;">
                <el-button link type="primary" icon="Document"></el-button>
              </router-link>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['credit:card:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['credit:card:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        @pagination="getList"/>
    </el-card>

    <!-- 添加或修改信用卡列对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="cardFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="持卡人" prop="holderId">
              <el-select v-model="form.holderId" placeholder="请选择持卡人" filterable clearable style="width: 100%;" @change="selectHolder" >
                <el-option v-for="item in holderList"
                           :key="item.id" :label="item.realName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单拆分模板" prop="billTemplateId">
              <el-select v-model="form.billTemplateId" placeholder="请选择账单拆分模板" filterable clearable style="width: 100%;">
                <el-option v-for="item in billTemplateList"
                           :key="item.id" :label="item.templateName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="POS商户" prop="posMerId">
              <el-select v-model="form.posMerId" value-key="id" placeholder="请选择POS商户" filterable clearable style="width: 100%;" @change="selectPosMer">
                <el-option v-for="item in posMerList"
                           :key="item.id"
                           :label="item.merName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫码商户" prop="qrMerId">
              <el-select v-model="form.qrMerId" value-key="id" placeholder="请选择扫码商户" filterable clearable style="width: 100%;" @change="selectQrMer">
                <el-option v-for="item in qrMerList"
                           :key="item.id"
                           :label="item.merName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="POS执行费率" prop="posRate">
              <el-input v-model="form.posRate" placeholder="请输入pos机的执行利率" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扫码执行费率" prop="qrRate">
              <el-input v-model="form.qrRate" placeholder="请输入扫码支付的执行利率" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用卡卡号" prop="cardNum">
              <el-input v-model="form.cardNum" placeholder="请输入信用卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡片状态" prop="state">
              <el-radio-group v-model="form.state">
                <el-radio v-for="dict in module_state" :key="parseInt(dict.value)" :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡总额度" prop="totalLimit">
              <el-input v-model="form.totalLimit" placeholder="请输入卡总额度" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余额度" prop="leftLimit">
              <el-input v-model="form.leftLimit" placeholder="请输入剩余额度" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余额度占比" prop="leftRate">
              <el-input v-model="form.leftRate" placeholder="请输入剩余额度占比" type="number">
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="临时额度" prop="tempLimit">
              <el-input v-model="form.tempLimit" placeholder="请输入临时额度" type="number">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账单日" prop="statementDay">
              <el-input v-model="form.statementDay" placeholder="请输入账单日" type="number" min="1" max="31">
                <template #prepend>每月</template>
                <template #append>日</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="还款日" prop="repaymentDay">
              <el-input v-model="form.repaymentDay" placeholder="请输入还款日" type="number" min="1" max="31">
                <template #prepend>每月</template>
                <template #append>日</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡片有效期" prop="periodValidity">
              <el-date-picker clearable v-model="form.periodValidity" type="date"
                              value-format="YYYY-MM-DD" placeholder="请选择卡片有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背面CVV编号" prop="cardCvv">
              <el-input v-model="form.cardCvv" placeholder="请输入背面CVV编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定微信号" prop="wxNo">
              <el-input v-model="form.wxNo" placeholder="请输入绑定微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定微信昵称" prop="wxNiceName">
              <el-input v-model="form.wxNiceName" placeholder="请输入绑定微信昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定手机号" prop="phoneNum">
              <el-input v-model="form.phoneNum" placeholder="请输入绑定手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行名称" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入银行名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联行号" prop="bankCode">
              <el-input v-model="form.bankCode" placeholder="请输入联行号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="businessUserId">
              <el-select v-model="form.businessUserId" placeholder="请选择业务员" filterable clearable style="width: 100%;" :disabled="form.id > 0">
                <el-option v-for="item in sysUserList"
                           :key="item.userId" :label="item.nickName + '(' + item.phonenumber + ')'"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Card" lang="ts">
import { listCard, getCard, delCard, addCard, updateCard } from '@/api/credit/card';

import sysUserApi, {listUserByRoleKey} from "@/api/system/user"
import { CardVO, CardQuery, CardForm } from '@/api/credit/card/types';
import {listNoPageHolder} from "@/api/credit/holder/index";
import {HolderVO} from "@/api/credit/holder/types";
import {listNoPageMer} from "@/api/credit/mer";
import {listNoPagePackage} from "@/api/credit/package";
import {listNoPageBillTemplate} from "@/api/credit/bill/template";
import {MerVO} from "@/api/credit/mer/types";
import {PackageVO} from "@/api/credit/package/types";
import {BillTemplateVO} from "@/api/credit/bill/template/types";
import {UserVO} from "@/api/system/user/types";

//新页面接收参数js
import { useRoute } from "vue-router"
//注意是useRoute
const route = useRoute()

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_state } = toRefs<any>(proxy?.useDict('module_state'));

const sysUserList = ref<UserVO[]>();
const cardList = ref<CardVO[]>([]);
const holderList = ref<HolderVO[]>([]);
const posMerList = ref<MerVO[]>([]);
const qrMerList = ref<MerVO[]>([]);
const packageList = ref<PackageVO[]>([]);
const billTemplateList = ref<BillTemplateVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);


const queryFormRef = ref<ElFormInstance>();
const cardFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CardForm = {
  id: undefined,
  holderId: undefined,
  cardNum: undefined,
  billTemplateId: undefined,
  statementDay: undefined,
  repaymentDay: undefined,
  totalLimit: undefined,
  leftLimit: undefined,
  leftRate: undefined,
  tempLimit: undefined,
  state: undefined,
  periodValidity: undefined,
  cardCvv: undefined,
  realName: undefined,
  posMerName: undefined,
  qrMerName: undefined,
  posMerId: undefined,
  qrMerId: undefined,
  posRate: undefined,
  qrRate: undefined,
  posNum: undefined,
  phoneNum: undefined,
  bankName: undefined,
  bankCode: undefined,
  wxNo: undefined,
  wxNiceName: undefined,
  businessUserId: undefined
}
const data = reactive<PageData<CardForm, CardQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    holderId: undefined,
    cardNum: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    holderId: [
      { required: true, message: "持卡人表id不能为空", trigger: "blur" }
    ],
    cardNum: [
      { required: true, message: "信用卡号不能为空", trigger: "blur" }
    ],
    billTemplateId: [
      { required: true, message: "账号拆分模板id不能为空", trigger: "blur" }
    ],
    statementDay: [
      { required: true, message: "账单日不能为空", trigger: "blur" }
    ],
    repaymentDay: [
      { required: true, message: "还款日不能为空", trigger: "blur" }
    ],
    totalLimit: [
      { required: true, message: "卡总额度不能为空", trigger: "blur" }
    ],
    leftLimit: [
      { required: true, message: "剩余额度不能为空", trigger: "blur" }
    ],
    leftRate: [
      { required: true, message: "剩余额度占有比例不能为空", trigger: "blur" }
    ],
    // tempLimit: [
    //   { required: true, message: "临时额度不能为空", trigger: "blur" }
    // ],
    state: [
      { required: true, message: "请选择卡片状态", trigger: "blur" }
    ],
    periodValidity: [
      { required: true, message: "卡片有效期不能为空", trigger: "blur" }
    ],
    cardCvv: [
      { required: true, message: "背面CVV编号不能为空", trigger: "blur" }
    ],
    realName: [
      { required: true, message: "持卡人姓名不能为空", trigger: "blur" }
    ],
    posMerId: [
      { required: true, message: "请选择pos机商户", trigger: "blur" }
    ],
    qrMerId: [
      { required: true, message: "请选择扫码商户", trigger: "blur" }
    ],
    posRate: [
      { required: true, message: "pos机的执行利率不能为空", trigger: "blur" }
    ],
    qrRate: [
      { required: true, message: "扫码支付的执行利率不能为空", trigger: "blur" }
    ],
    posNum: [
      { required: true, message: "pos机终端号不能为空", trigger: "blur" }
    ],
    phoneNum: [
      { required: true, message: "绑定手机号不能为空", trigger: "blur" }
    ],
    bankName: [
      { required: true, message: "银行名称不能为空", trigger: "blur" }
    ],
    bankCode: [
      { required: true, message: "联行号不能为空", trigger: "blur" }
    ],
    wxNo: [
      { required: true, message: "绑定微信号不能为空", trigger: "blur" }
    ],
    wxNiceName: [
      { required: true, message: "绑定微信昵称不能为空", trigger: "blur" }
    ],
    businessUserId: [
      { required: true, message: "业务人员id不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询信用卡列列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCard(queryParams.value);
  cardList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


/** 查询信用卡持卡人列表 */
const getHolderList = async () => {
  const res = await listNoPageHolder(queryParams.value);
  holderList.value = res.data;
}

/** 查询 业务员列表 */
const getSysUserList = async () => {
  const res = await sysUserApi.listUserByRoleKey("business");
  sysUserList.value = res.data;
}


function back() {
  if (proxy?.$route.query.noGoBack) {
    proxy.$router.push({ path: "/" });
  } else {
    proxy?.$router.go(-1);
  }
}


const selectPosMer = (e:any) =>{
  console.log('selectPosMer',e)
  for (let index in posMerList.value){
    if(e == posMerList.value[index].id){
      form.value.posRate = posMerList.value[index].posRate;
      form.value.posMerName = posMerList.value[index].merName;
    }
  }
  // form.value.posMerId = e.id;
  console.log('form.value.posMerId',form.value.posMerId)
}

const selectQrMer = (e:any) =>{
  console.log('selectQrMer',e)
  for (let index in qrMerList.value){
    if(e == qrMerList.value[index].id){
      form.value.qrRate = qrMerList.value[index].qrRate;
      form.value.qrMerName = qrMerList.value[index].merName;
    }
  }
  console.log('form.value.qrMerId',form.value.qrMerId)
}

const selectHolder = (e:any) =>{
  console.log('selectHolder',e)
  for (let index in holderList.value){
    if(e == holderList.value[index].id){
      form.value.realName = holderList.value[index].realName;
      form.value.phoneNum = holderList.value[index].phoneNum;
    }
  }
}




/** 查询收款商户列表 */
const getMerList = async (isQr:number) => {
  let param = {
    isQr:isQr,
  }
  const res = await listNoPageMer(param);
  if(isQr == 0){
    posMerList.value = res.data;
  }else{
    qrMerList.value = res.data;
  }
}


/** 查询套餐列表 */
const getPackageList = async () => {
  const res = await listNoPagePackage(queryParams.value);
  packageList.value = res.data;
}


/** 查询信用卡列列表 */
const getBillTemplateList = async () => {
  const res = await listNoPageBillTemplate(queryParams.value);
  billTemplateList.value = res.data;
}



/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  cardFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CardVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加信用卡列表";
  getHolderList();
  getMerList(0);
  getMerList(1);
  getPackageList();
  getBillTemplateList();
  getSysUserList();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CardVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getCard(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改信用卡列表";
  getHolderList();
  getMerList(0);
  getMerList(1);
  getPackageList();
  getBillTemplateList();
  getSysUserList();
}

/** 提交按钮 */
const submitForm = () => {
  cardFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCard(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addCard(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: CardVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除信用卡列表编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delCard(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/card/export', {
    ...queryParams.value
  }, `card_${new Date().getTime()}.xlsx`)
}

onMounted(() => {

  console.log('接收参数 ', route.query.hId)//输出的即为接收到的参数
  if(route.query.hId != undefined){
    queryParams.value.holderId = parseInt(route.query.hId as string) ;
    form.value.holderId = parseInt(route.query.hId as string) ;
  }

  getList();
});
</script>
